Search


📜 [專欄新文章] 如何減少transaction gas cost
✍️ ...

  • Share this:


📜 [專欄新文章] 如何減少transaction gas cost
✍️ Brian Po-han Chen
📥 歡迎投稿: https://medium.com/taipei-ethereum-meetup #徵技術分享文 #使用心得 #教學文 #medium
因為做產品的時候,當然希望成本越低越好,所以簡單的做了一個實驗,測試合約大致如下(跟原來做實驗的合約有一點不一樣,但是邏輯是一樣的):

contract Test { mapping (uint => bytes32[]) Data; function setData0(uint idx, bytes32[] dataSet) returns (bool) { Data[idx] = dataSet; }

function setData1(uint[] idxs, bytes32[] dataSet) returns (bool) { uint index_dataset = 0; for (uint i = 0; i < idxs.length; i += 2) { for (uint j = 0; j < idxs[i+1]; j++) { Data[idxs[i]].push(dataSet[index_dataset + j]); } index_dataset += idxs[i+1]; } }}

我希望在某一個key底下放一個bytes32 array,希望用最少的交易來達到,第一個function是一筆一筆送;而第二個function則是在第一個參數放入下述定義的array,

[idx, idx_num, idx, idx_num, …, idx, idx_num]

第二個參數則是把所有要放進去的bytes32值,藉由第一個參數的idx要放idx_num個bytes32去全部塞在同一個交易中.

實驗結果如下:

在Execution Gas Cost上,setData0大概都會略少於setData1,這樣似乎告訴我們不要做這麼複雜比較好?那我們來看一下Transaction Gas Cost

結果setData0的gas cost就漸漸的越來越大,這是因為每次送交易,都會有base gas cost大約在20000左右,也會隨變數增加漸漸變大,所以一次把資料全部送進去合約雖然一開始沒有太大差異,但隨著資料量增加,可以省下不少gas.

另外,得注意block gas limit以免超過限制,還有礦工可能會因為gas消耗太大不願意幫你打包等等,所以應該要適量的控制gas consume.

如何減少transaction gas cost was originally published in Taipei Ethereum Meetup on Medium, where people are continuing the conversation by highlighting and responding to this story.

👏 歡迎轉載分享鼓掌


Tags:

About author
not provided
We have regular meeting twice per month on discussing blockchain technology, smart contracts and DApps development! We would love to have you join us!
View all posts